// 部分摘取自https://open-doc.dingtalk.com
// 但是有的是内部的接口，尚未向外公开，上面的地址也没有文档

import urlParams from "./urlParams";
import wpo from '@ali/retcodelog';
const dd = window.dd;
import { getBrowserInfo } from "./browser";
module.exports = exports = {
  // 升级，下载最新版
  toUploadNewestVersion(cb) {
    let url = "";

    if (dd.android) {
      url = "http://www.dingtalk.com/android/d/";
    } else {
      url = "http://www.dingtalk.com/ios/d/";
    }
    if (cb) {
      cb(url);
    }
  },
  goBack({ success = () => {} }) {
    dd.biz.navigation.goBack({
      success
    });
  },
  close() {
    dd.biz.navigation.close();
  },
  pullToRefresh() {
    dd.ui.pullToRefresh.enable();
  },
  openSingleChat({ corpId, userId, cb }) {
    dd.biz.chat.openSingleChat({
      corpId, // 企业id
      userId, // 用户的工号
      onSuccess: function(res) {
        if (!cb) {
          cb(res);
        }
      }
    });
  },

  previewImage({ urls, current, cb, errCb }) {
    dd.biz.util.previewImage({
      urls, //图片地址列表
      current, //当前显示的图片链接
      onSuccess: function(result) {
        if (cb) cb(result);
      },
      onFail: function(err) {
        if (errCb) errCb(err);
      }
    });
  },
  setTitle({ title, subTitle }) {
    dd.biz.navigation.setTitle({
      title,
      subTitle
    });
  },
  setRight({ text, onClick, show = true }) {
    dd.biz.navigation.setRight({
      control: !!onClick,
      show,
      text,
      onSuccess() {
        onClick();
      }
    });
  },
  setLeft({ text, onClick, show }) {
    dd.biz.navigation.setLeft({
      control: !!onClick,
      show,
      text,
      onSuccess() {
        onClick();
      }
    });
  },
  getCurrentUser(cb, errCb) {
    window.dd.biz.user.get({
      onSuccess: function(info) {
        cb(info);
      },
      onFail: function(err) {
        errCb(err);
      }
    });
  },
  // 约定search 只能传userId
  openLink(url) {
    const isEntireLink = url.indexOf("http") !== -1;

    if (!isEntireLink) {
      const [search, hash] = url.split("#");
      const hasUserId = search.indexOf("userId") !== -1;
      let newSearch = window.location.search;
      if (hasUserId) {
        if (newSearch.indexOf("userId") !== -1) {
          // url有userId需要替换
          const userId = search.substring(8);
          newSearch = window.location.search.replace(
            /userId=((\w|-|\s)+)/gi,
            `userId=${userId}`
          );
        } else if (newSearch === "") {
          // window.location.search 为空，直接覆盖
          newSearch = search;
        } else {
          // 否则 append search
          newSearch = window.location.search + "&" + search.slice(1);
        }
      }
      dd.biz.util.openLink({
        url: `${window.location.origin}${window.location
          .pathname}${newSearch}#${hash}`,
        onFail: function(err) {
          console.log(err); // eslint-disable-line
        }
      });
    } else {
      dd.biz.util.openLink({
        url,
        onFail: function(err) {
          console.log(err); // eslint-disable-line
        }
      });
    }
  },
  // 弹出确认升级的对话框
  confirm({ title = "提示", message = "", buttonLabels, cb }) {
    dd.device.notification.confirm({
      message,
      title,
      buttonLabels,
      onSuccess: function(result) {
        cb(result);
      }
    });
  },
  create({ users, corpId, bizType = 2,alertType = 2, text, cb }) {
    if (exports.compareVersion("3.5.1", dd.version, true)) {
      dd.biz.ding.create({
        users, // 用户列表，工号
        corpId, // 企业id
        alertType,
        // type: 1, // 附件类型 1：image  2：link
        // alertType: 2, // 钉发送方式 0:电话, 1:短信, 2:应用内
        // alertDate: { format: "yyyy-MM-dd HH:mm", value: "2015-05-09 08:00" },
        // attachment: {
        //   images: [""]
        // }, // 附件信息
        text, // 正文
        bizType, // 业务类型 0：通知DING；1：任务；2：会议；
        onSuccess(result) {
          if (cb) cb(result);
        }
      });
    } else {
      exports.confirm({
        title: "",
        message: "请升级钉钉到最新版体验该功能",
        buttonLabels: ["以后再说", "立即升级"],
        cb: result => {
          if (result.buttonIndex === 1) {
            exports.toUploadNewestVersion();
          }
        }
      });
    }
  },
  creatGroup({ corpId, users, cb }) {
    dd.biz.contact.createGroup({
      corpId,
      users,
      onSuccess(result) {
        if (cb) cb(result);
      }
    });
  },
  //还有些参数，需要可扩展
  toast({ icon = "", text, onSuccess, onFail }) {
    window.dd.device.notification.toast({
      icon,
      text,
      onSuccess,
      onFail
    });
  },
  alert({ message = "", title = "", buttonName = "我知道了", ...rest }) {
    dd.device.notification.alert({
      message,
      title,
      buttonName,
      ...rest
    });
  },
  //选人
  chooseContact({
    title,
    corpId,
    isNeedSearch = true,
    users = [],
    disabledUsers = [],
    onSuccess
  }) {
    window.dd.biz.contact.choose({
      title, //标题
      corpId, //加密的企业 ID，
      isNeedSearch,
      onSuccess,
      users,
      disabledUsers,
      onFail(err) {
        console.log(err); // eslint-disable-line
      }
    });
  },
  // 自定义选人
  // see also: https://open-doc.dingtalk.com/docs/doc.htm?spm=a219a.7629140.0.0.Co43cq&treeId=171&articleId=104927&docType=1
  chooseCustomContact({ title, users, corpId, onSuccess }) {
    window.dd.biz.customContact.choose({
      title, //标题
      users, //一组员工userid
      corpId, //加密的企业 ID，
      onSuccess,
      onFail(err) {
        console.log(err); // eslint-disable-line
      }
    });
  },

  openConversation({ uid, title, content, image, url, type }) {
    dd.internal.chat.openConversation({
      uid,
      title,
      content,
      image,
      url,
      type, //0是文本，1是Link
      onFail(err) {
        console.log(err); // eslint-disable-line
      }
    });
  },
  departmentsPicker({ corpId, multiple, cb, errCb, ...rest }) {
    dd.biz.contact.departmentsPicker({
      corpId,
      ...rest,
      multiple,
      onSuccess: function(result) {
        cb(result);
      },
      onFail: function(err) {
        if (err && errCb) {
          errCb(err);
        }
      }
    });
  },
  showPreloader({ text = "使劲加载中..", showIcon = true, onSuccess, onFail } = {}) {
    window.dd.device.notification.showPreloader({
      text, //loading显示的字符，空表示不显示文字
      showIcon, //是否显示icon，默认true
      onSuccess,
      onFail
    });
  },
  hidePreloader({ onSuccess, onFail } = {}) {
    window.dd.device.notification.hidePreloader({
      onSuccess,
      onFail
    });
  },
  /**
   * 如果前一个版本号大于后一个版本号（还要处理是否等于情况），返回true
   * @param {一个版本号} pre 
   * @param {另一个版本号} next 
   * @param {是否包括等号} equal 
   */
  compareVersion(pre, next, equal) {
    return dd.compareVersion(pre, next, equal);
  },

  /*
   * 人和部门都可以选择的组件
   */
  complexPicker({ corpId, cb, errCb, ...rest }) {
    dd.biz.contact.complexPicker({
      corpId,
      ...rest,
      onSuccess: function(result) {
        cb(result);
      },
      onFail: function(err) {
        if (err && errCb) {
          errCb(err);
        }
      }
    });
  },
  /**
     * 分享的JSAPI
     * @param {*} param0 
     */
  share({ type, url, title, content, image, cb }) {
    dd.biz.util.share({
      type, // Number, 分享类型，0:全部组件 默认； 1:只能分享到钉钉；2:不能分享，只有刷新按钮
      url, // String, url地址
      title, // String, 分享标题
      content, // String, 分享内容
      image, // String, 分享的图片
      onSuccess: function(res) {
        cb && cb(res);
        //onSuccess将在分享完成之后回调
      },
      onFail: function(err) {
        console.log(err);
      }
    });
  },
  notify(params) {
    dd.internal.notify.send(params)
  },
  //选群组 返回值 cid title
  pickConversation(params = {}) {

    return new Promise((resolve, reject) => {
      dd.biz.chat.pickConversation({
        corpId: params.corpId || urlParams.getUrlSearchParam("corpId"),
        isConfirm: params.isConfirm || true,
        onSuccess: function (res) {
          resolve(res);
        },
        onFail: function (error) {
          wpo.log("pickConversation" + JSON.stringify(error));
          reject(error);
        }
      })
    })
  },
 
  //打开群聊会话 corpId  cid
  chatOpen(params) {
    dd.biz.chat.open({
      corpId: params.corpId || urlParams.getUrlSearchParam("corpId"),
      cid: params.cid
    });
  },

  //actionSeeet
  actionSheet({ title = "", cancelButton = "", otherButtons = [], onSuccess }) {
    const isAndroid = getBrowserInfo().android;
    const realCancel = isAndroid ? "" : cancelButton;
    dd.device.notification.actionSheet({
      title: title,
      cancelButton: realCancel, //取消按钮文本
      otherButtons: otherButtons,
      onSuccess: onSuccess
    })
  }
};
